"""
主题: 创建缓存实例
问题: 在创建一个类的对象时，如果之前使用同样参数创建过这个对象， 你想返回它的缓存引用。
提示 : 
"""

# The class in question
class Spam:
    def __init__(self, name):
        self.name = name

# Caching support
import weakref

_spam_cache = weakref.WeakValueDictionary()


def get_spam(name):
    if name not in _spam_cache:
        s = Spam(name)
        _spam_cache[name] = s
    else:
        s = _spam_cache[name]
    return s


# Note: This code doesn't quite work
class Spam1:
    _spam_cache = weakref.WeakValueDictionary()

    def __new__(cls, name):
        print('Spam1__new__')
        if name in cls._spam_cache:
            return cls._spam_cache[name]
        else:
            self = super().__new__(cls)
            cls._spam_cache[name] = self
            return self

    def __init__(self, name):
        print('Initializing Spam')
        self.name = name

def recipe1():
    import logging

    a = logging.getLogger('foo')
    b = logging.getLogger('bar')
    print(f"{ a is b = }")
    c = logging.getLogger('foo')
    print(f"{ a is c = }")    

def recipe2():
    a = get_spam('foo')
    b = get_spam('bar')
    print(f"{ a is b = }")
    c = get_spam('foo')
    print(f"{ a is c = }")

def recipe3():
    s = Spam1('Dave')
    t = Spam1('Dave')
    print(f"{ s is t = }")

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()

if __name__ == '__main__':
    main()  